import React, { useState, useEffect, useRef } from 'react';
// Vant 官方提供了一份默认的省市区数据
import { areaList } from '@vant/area-data'
//搜索        省市区选择
import { Search, Button, Area } from 'react-vant';
//导航栏  下拉菜单
import { NavBar, Dropdown } from 'antd-mobile'
//map的加载器
import AMapLoader from "@amap/amap-jsapi-loader";
import { useNavigate } from 'react-router-dom'
import { LocationO, Phone } from '@react-vant/icons';
import './Dinelist.scss'
import { debounce } from 'lodash';//导入防抖函数

export default function Dinelist() {
    let navigate = useNavigate()
    const [value, setValue] = useState('');
    const [curProvince, setCurProvince] = useState('');//当前选中的省
    const [curCity, setCurCity] = useState('保定市');//当前选中的市
    const [curCounty, setCurCounty] = useState('');//当前选中的区
    let map = null;
    let [AMap, setAMap] = useState(null);
    let [searchValue, setSearchValue] = useState('人民医院')
    let [list, setList] = useState([])
    const ref = useRef(null)//获取下拉菜单
    // 假数据
    const arr = [
        {
            id: 1,
            name: '谭记旺品(秀兰·锦观城店)',
            space: 1.2,
            district: '河北省 保定市 竞秀区'
        },
        {
            id: 2,
            name: '谭记旺品(保广店)',
            space: 1.9,
            district: '河北省 保定市 竞秀区'
        },
        {
            id: 3,
            name: '大吉利潮汕牛肉火锅(保百京南一品店)',
            space: 3.4,
            district: '河北省 保定市 莲池区'
        },
        {
            id: 4,
            name: '大吉利潮汕牛肉火锅(未来石万达店)',
            space: 3.9,
            district: '河北省 保定市 莲池区'
        },
        {
            id: 5,
            name: '沃伦尼烤肉自助料理(嘉德万达店)',
            space: 1.4,
            district: '河北省 保定市 莲池区'
        },
        {
            id: 6,
            name: '三三得九鲜切牛肉自助火锅(嘉德万达店)',
            space: 1.4,
            district: '河北省 保定市 莲池区'
        },
    ]
    // 使用防抖函数处理搜索
    const handleSearch = debounce((val) => {
        setSearchValue(val)// 处理搜索逻辑
    }, 500);
    useEffect(() => {
        AMapLoader.load({
            key: "b160997910352f8de07199b2cced3e7e", // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ["AMap.AutoComplete", 'AMap.PlaceSearch'], // 添加输入提示插件
        })
            .then((AMap) => {
                setAMap(AMap)
                map = new AMap.Map("container", {   //访问成功则创建map对象
                    // 设置地图容器id
                    viewMode: "3D", // 是否为3D地图模式
                    zoom: 11, // 初始化地图级别
                    center: [116.397428, 39.90923], // 初始化地图中心点位置
                });
                map.on('complete', function () {      //map的生命周期方法
                    var autoOptions = {
                        input: "input_id",
                        city: curCity,//搜索的城市
                    };
                    //地图图块加载完成后触发
                    var auto = new AMap.AutoComplete(autoOptions);  //实例化AutoComplete模块
                    auto.search(searchValue, function (status, result) {
                        // 搜索成功时，result即是对应的匹配数据
                        console.log(result);
                        if (result.tips) {
                            setList(result.tips.slice(1))
                            console.log('获取到数据了！');
                        }
                    })
                    var placeSearch = new AMap.PlaceSearch({
                        map: map,          //文档中的map参数
                    });  //构造地点查询类
                    auto.on("select", function (e) {
                        console.log(e);
                        placeSearch.setCity(e.poi.adcode);
                        placeSearch.search(e.poi.name);  //关键字查询查询
                    });//注册监听，当选中某条记录时会触发
                });
            })
            .catch((e) => {
                console.log(e);
            });
        return () => {
            map?.destroy();
        };
    }, [curCity, searchValue]);
    // console.log(list);
    return (
        <div id='dinelist'>
            <NavBar onBack={() => { navigate('/User_Home/Consultation') }} style={{ background: '#fff' }}>选择门店</NavBar>
            <div className="search">
                <Button size='mini' icon={<LocationO />} type='primary' />
                <Dropdown ref={ref}>
                    <Dropdown.Item key='sorter' title={curCity}>
                        <div style={{ padding: 12 }}>
                            {/* Vant 官方提供了一份默认的省市区数据 */}
                            <Area itemHeight='30' title='' areaList={areaList} columnsNum={2} onConfirm={v => {
                                console.log(v)//['110000', '110100', '110101']
                                let curProvinceValue = Number(v[0])//当前省地区码
                                let curCityValue = Number(v[1])//当前市地区码
                                let curCountyValue = Number(v[2])//当前区地区码
                                setCurProvince(areaList.province_list[curProvinceValue])
                                setCurCity(areaList.city_list[curCityValue])
                                setCurCounty(areaList.county_list[curCountyValue])
                                // console.log(areaList.province_list[curProvinceValue]);
                                // console.log(areaList.city_list[curCityValue]);
                                // console.log(areaList.county_list[curCountyValue]);
                                ref.current?.close()
                            }} />
                            {/* <div id="container" style={{ height: "40vh", width: "100vw", marginTop: "10px" }}></div> */}
                        </div>
                    </Dropdown.Item>
                </Dropdown>
                <Search
                    style={{ width: '75%' }}
                    showAction
                    id="input_id" // 替换为实际输入框的 id
                    value={searchValue}
                    onChange={(val) => {
                        handleSearch(val)
                    }}
                    placeholder="请输入搜索关键词"
                />
            </div>
            {
                list.length ?
                    list.map(ele => <div key={ele.id} className="main" onClick={() => {
                        navigate('/choosenumber')
                        localStorage.setItem('dineInObj', JSON.stringify(ele))
                    }}>
                        <div className="left">
                            <h4>{ele.name}</h4>
                            <div id='middle'>
                                <span>2.1km</span>
                                <span>{ele.district}{ele.address}</span>
                            </div>
                            <div id="low">
                                <button>营业中</button>
                                <span>10:30-23:00</span>
                            </div>
                        </div>
                        <div className="right">
                            {/* <button>去下单</button> */}
                            {/* <div className="button">
                                <Button size='mini' icon={<Phone />} type='primary' />
                                <Button size='mini' icon={<LocationO />} type='primary' />
                            </div> */}

                        </div>
                    </div>)
                    :
                    <>
                        {arr.map(ele => <div key={ele.id} className="main" onClick={() => {
                            navigate('/choosenumber')
                            localStorage.setItem('dineInObj', JSON.stringify(ele))
                        }}>
                            <div className="left">
                                <h4>{ele.name}</h4>
                                <div id='middle'>
                                    <span>{ele.space}km</span>
                                    <span>{ele.district}</span>
                                </div>
                                <div id="low">
                                    <button>营业中</button>
                                    <span>10:30-23:00</span>
                                </div>
                            </div>
                            <div className="right">
                                {/* <button>去下单</button> */}
                                {/* <div className="button">
                                    <Button size='mini' icon={<Phone />} type='primary' />
                                    <Button size='mini' icon={<LocationO />} type='primary' />
                                </div> */}

                            </div>
                        </div>)}
                    </>
            }
            <div id="container" style={{ height: "1vh", width: "1vw", marginTop: "10px" }}></div>
        </div>
    )
}
